package cn.yhsoft.fs;

import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LiYong
 */
@Component
public class FsTurboDao {
    @Autowired
    private DataSource dataSource;

    public FsTurboDao(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public int insert(FsTurboDto fsTurboDto, boolean isImage) {
        var insertSql = "insert into fs_turbo(id, scenes, inner_type, bus_id,source, md5, crc, create_time, save_file_name, file_name, path) values (?,?,?,?,?,?,crc32(?),?,?,?,?)";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.update(insertSql, fsTurboDto.getId(), fsTurboDto.getScenes(), isImage ? 1 : 0, fsTurboDto.getBusId(), fsTurboDto.isSource(), fsTurboDto.getMd5(), fsTurboDto.getMd5(), fsTurboDto.getCreateTime(), fsTurboDto.getSaveFileName(), fsTurboDto.getFileName(), fsTurboDto.getPath());
    }

    public int deleteByScenesAndBus(String scenes, String busId) {
        //TODO: 这里应该更改为软删除，留下的源文件还可以使用
        var delSql = "delete from fs_turbo where scenes=? and bus_id=?";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.update(delSql, scenes, busId);
    }

    public int deleteById(String id) {
        //TODO: 这里应该更改为软删除，留下的源文件还可以使用
        var delSql = "delete from fs_turbo where id=?";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.update(delSql, id);
    }

    public FsTurboDto getSourceFileByMd5(String fileMd5, boolean isImage) {
        var querySql = "select id, scenes, inner_type, bus_id, source, md5, create_time, save_file_name, file_name, path from fs_turbo where source = true and inner_type = " + (isImage ? 1 : 0) + " and crc = crc32(?)";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        var dtos = jdbcTemplate.query(querySql, BeanPropertyRowMapper.newInstance(FsTurboDto.class), fileMd5);
        if (dtos.size() == 0) {
            return null;
        }
        if (dtos.size() == 1) {
            return dtos.get(0);
        }
        //通过crc方案进行检索出来如果有多条，可能存在md5不一致的情况
        for (FsTurboDto dto : dtos) {
            if (dto.getMd5().equals(fileMd5)) {
                return dto;
            }
        }
        throw new RuntimeException("Get source file info by CRC error");
    }

    public FsTurboDto getById(String id) {
        var querySql = "select id, scenes, inner_type,bus_id, source, md5, create_time, save_file_name, file_name, path from fs_turbo where id = ?";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        var dtos = jdbcTemplate.query(querySql, BeanPropertyRowMapper.newInstance(FsTurboDto.class), id);
        return dtos.size() == 0 ? null : dtos.get(0);
    }

    public List<FsTurboDto> getByBusId(String scenes, String busId, int offset, int limit) {
        var querySql = "select id, scenes, inner_type,bus_id, source, md5, create_time, save_file_name, file_name, path from fs_turbo where scenes=? and bus_id=? limit ? offset ?";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.query(querySql, BeanPropertyRowMapper.newInstance(FsTurboDto.class), scenes, busId, limit, offset);
    }

    public List<FsTurboDto> getByIdOrMd5(String id, String md5) {
        var querySql = "select id, scenes, inner_type, bus_id, source, md5, create_time, save_file_name, file_name, path from fs_car where id = ? or crc = crc32(?)";
        var jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.query(querySql, BeanPropertyRowMapper.newInstance(FsTurboDto.class), id, md5);
    }

    public List<FsTurboDto> getByIds(String[] ids) {
        var result = new ArrayList<FsTurboDto>();
        if (ids.length == 0) {
            return result;
        }
        var jdbcTemplate = new JdbcTemplate(dataSource);
        var baseSql = "select id, scenes, inner_type, bus_id, source, md5, create_time, save_file_name, file_name, path from fs_turbo where id in (";
        //这里设定1000个id进行分批检索
        var split = 1000;
        var index = 0;
        var querySql = new StringBuilder(baseSql);
        var params = new ArrayList<Object>();
        do {
            querySql.append("?");
            params.add(ids[index]);
            index++;
            if (index % split == 0 || index == ids.length) {
                querySql.append(")");
                var tempLs = jdbcTemplate.query(querySql.toString(), BeanPropertyRowMapper.newInstance(FsTurboDto.class), params.toArray());
                result.addAll(tempLs);
                querySql = new StringBuilder(baseSql);
                params.clear();
            } else {
                querySql.append(",");
            }
        }
        while (ids.length > index);
        return result;
    }
}
